import {
  addClassUsingPost,
  getAllMajorUsingGet,
  updateClassUsingPut,
} from '@/services/student-management-system/banjimokuai';
import { Form, Input, message, Select } from 'antd';
import { forwardRef, useEffect, useImperativeHandle, useState } from 'react';

export interface UpdateClassProps {
  editClass?: API.ClassDTO;
  onCloseModal?: () => void;
}

export interface UpdateClassMethods {
  submitForm: () => Promise<boolean>;
}

interface optionsType {
  value: string | undefined;
  label: string | undefined;
}

const UpdateClass = forwardRef<UpdateClassMethods, UpdateClassProps>((props, ref) => {
  const { editClass, onCloseModal } = props;
  const [majorOptions, setMajorOptions] = useState<optionsType[]>([]);
  const [form] = Form.useForm();

  const submitForm = async (): Promise<boolean> => {
    // 获取表单提交数据
    const values = await form.validateFields();
    const res = editClass?.id
      ? await updateClassUsingPut({ ...values, id: editClass.id })
      : await addClassUsingPost(values);

    if (res.code === 200) {
      message.success('操作成功');
      onCloseModal?.();
      return true;
    } else {
      message.error('操作失败：' + res.msg);
      return false;
    }
  };

  useEffect(() => {
    const fetchData = async () => {
      const res = await getAllMajorUsingGet();
      if (res.code === 200) {
        setMajorOptions(
          res.data?.map((major) => ({
            value: major,
            label: major,
          })) ?? [],
        );
      }
    };
    fetchData();

    if (editClass) {
      form.setFieldsValue({
        className: editClass.className,
        grade: editClass.grade,
        major: editClass.major,
      });
    }
  }, [editClass, form]);

  useImperativeHandle(ref, () => ({
    submitForm,
  }));

  return (
    <Form form={form} labelCol={{ span: 8 }} wrapperCol={{ span: 16 }} autoComplete="off">
      <Form.Item label="班级名称" name="className" rules={[{ required: true }]}>
        <Input />
      </Form.Item>

      <Form.Item label="年级" name="grade" rules={[{ required: true }]}>
        <Input />
      </Form.Item>

      <Form.Item label="专业" name="major" rules={[{ required: true }]}>
        <Select placeholder="选择专业" optionFilterProp="label" options={majorOptions} />
      </Form.Item>
    </Form>
  );
});

export default UpdateClass;
